package com.qjz.diancan.manager.interceptor;


import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        // 获取请求方式
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;  // 如果是跨域预检请求，直接放行
        }
        // 获取 Authorization 头
        String authorizationHeader = request.getHeader("Authorization");
        if (StrUtil.isEmpty(authorizationHeader) || !authorizationHeader.startsWith("Bearer ")) {
            responseNoLoginInfo(response);
            return false;
        }
        // 放行
        return true;
    }

    private void responseNoLoginInfo(HttpServletResponse response) throws IOException
    {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401, \"message\":\"Unauthorized\"}");
        response.getWriter().flush();
    }
}
